<template>
  <div class="app-container">
    <div class="sluice-header">
      <span>闸坝名称：</span>
      <el-input class="zb-name" v-model="watergatename" size="small" placeholder="请输入闸坝名称"></el-input>
      <span class="sluice-header-span">行政区划：</span>
      <el-select size="small" v-model="address" placeholder="请选择行政区划">
        <el-option v-for="item in regionList" :key="item.code" :label="item.name" :value="item.code"></el-option>
      </el-select>
      <span class="sluice-header-span">所属河流：</span>
      <el-select v-model="riverid" placeholder="请选择所属河流" size="small">
        <el-option v-for="dict in riverList" :key="dict.value" :label="dict.label" :value="dict.value"></el-option>
      </el-select>
      <el-button class="query-btn" type="primary" icon="el-icon-search" size="mini" @click="handleQuery">查询</el-button>
      <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
    </div>
    <div class="sluice-sub-header">
      <el-button type="primary" icon="el-icon-plus" size="mini" plain v-hasPermi="['system:user:add']"
        @click="addForm">新增</el-button>
      <!-- <el-button type="success" plain icon="el-icon-edit" size="mini" v-hasPermi="['system:user:edit']">修改</el-button> -->
      <el-button type="danger" icon="el-icon-delete" size="mini" plain v-hasPermi="['system:user:remove']"
        @click="handleDelete">删除</el-button>
      <el-button type="warning" icon="el-icon-download" size="mini" plain
        v-hasPermi="['system:user:export']" @click="handleExport">导出</el-button>
    </div>
    <div v-loading="loading" class="sluice-table">
      <el-table ref="multipleTable" :data="tableData" tooltip-effect="dark" style="width: 100%"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55">
        </el-table-column>
        <el-table-column label="闸坝名称">
          <template slot-scope="scope">{{ scope.row.watergatename }}</template>
        </el-table-column>
        <el-table-column prop="address" label="行政区划">
        </el-table-column>
        <el-table-column prop="rivername" label="所属河流" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="watergatetype" label="闸口类型" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="watertypename" label="水体类型" show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="maxflow" label="最大流量(m3/s)" show-overflow-tooltip>
        </el-table-column>
        <el-table-column label="操作" align="center" width="150">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:menu:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:menu:remove']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog title="添加闸口信息" :visible.sync="dialogFormVisible">
      <el-form ref="form" label-position="right" :model="gateData" :rules="ruleForm" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="闸坝名称" prop="watergatename">
              <el-input v-model="gateData.watergatename" placeholder="请输入闸坝名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="闸坝类型">
              <el-select v-model="gateData.intercepttype" class="select-width" placeholder="请选择闸坝类型">
                <el-option v-for="dict in dict.type.zk_intercept_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="闸口类型">
              <el-select v-model="gateData.watergatetypecode" class="select-width" placeholder="请选择闸口类型">
                <el-option v-for="dict in dict.type.zk_water_gate_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="水体类型">
              <el-select v-model="gateData.watertype" class="select-width" placeholder="请选择水体类型">
                <el-option v-for="dict in dict.type.zk_water_type" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="经度" prop="longitude">
              <el-input v-model="gateData.longitude" placeholder="请输入经度"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="纬度" prop="latitude">
              <el-input v-model="gateData.latitude" placeholder="请输入纬度"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="行政区划">
              <el-select class="select-width" v-model="gateData.addresscode" placeholder="请选择行政区划">
                <el-option v-for="item in regionList" :key="item.code" :label="item.name"
                  :value="item.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属河流">
              <el-select v-model="gateData.riverid" class="select-width" placeholder="请选择所属河流">
                <el-option v-for="dict in riverList" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="所属支流、干流">
              <el-select v-model="gateData.stream" class="select-width" placeholder="请选择所属支流、干流">
                <el-option v-for="dict in dict.type.primary_and_secondary" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调控方式">
              <el-input v-model="gateData.regulationmode" placeholder="请输入调控方式"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="最大流量">
              <el-input placeholder="请输入内容" v-model="gateData.maxflow">
                <template slot="append">（立方/秒）</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="调度单位">
              <el-input v-model="gateData.regulationunit" placeholder="请输入调度单位"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="开启状态">
              <el-switch v-model="gateData.openclose" active-color="#13ce66" inactive-color="#ff4949">
              </el-switch>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注">
              <el-input type="textarea" placeholder="请输入备注" v-model="gateData.remark" maxlength="70" show-word-limit>
              </el-input>
            </el-form-item>
          </el-col>

        </el-row>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" :loading="submitLoading" @click="addSlice">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getwatergateList, addwatergate, removewatergate, getwatergateinfo, editwatergate } from '@/api/dataResources/monitorData/sluiceGate.js'
import { getRegionList } from '@/api/dataResources/monitorData/region.js'
import { getRiverSelect } from "@/api/dataResources/monitorData/section.js";
export default {
  name: "SluiceGate",
  dicts: ["sys_region", "zk_intercept_type", "zk_water_gate_type", "zk_water_type", "primary_and_secondary"],
  data() {
    return {
      riverid: "",
      watergatename: "", //闸坝名称
      address: "",
      // 遮罩层
      loading: true,
      dialogFormVisible: false,
      submitLoading: false,
      tableData: [],
      choseList: [],
      gateData: {
        watergatetypecode: '',
        riverid: '',
        watergatename: '', //闸口名称
        address: '', //地址
        rivername: '', //所属河流
        watergatetype: '', //闸口类型
        watertype: '', //水体类型
        maxflow: '', //最大流量
        intercepttype: '', //闸坝类型
        longitude: '', //经度
        latitude: '', //纬度
        stream: '', //所属支流、干流
        regulationmode: '', //调度方式
        regulationunit: '', //调度单位
        openclose: true, //开启状态
      },
      ruleForm: {
        watergatename: [
          { required: true, message: '请输入闸坝名称', trigger: 'blur' }
        ],
        longitude: [
          { required: true, message: '请输入经度', trigger: 'blur' },
        ],
        latitude: [
          { required: true, message: '请输入纬度', trigger: 'blur' },
        ]
      },
      riverList: [],
      regionList: [],
    }
  },
  created() {
    this.getsshl();
    this.getRegionList();
    this.query()
  },
  mounted() {
  },

  methods: {
    handleExport(){
      this.download('/base/watergate/export',{}, '闸口信息.xlsx')
    },
    //获取所属河流下拉选项数据
    getsshl() {
      getRiverSelect().then((response) => {
        this.riverList = response.data.map((item) => ({
          value: item.id,
          label: item.rivername,
        }));
      });
    },


    async getRegionList() {
      let res = await getRegionList();
      if (res.code == 200) {
        this.regionList = res.rows;
      }
    },
    // 初始化表单数据
    initFormData() {
      this.gateData = {
        watergatetypecode: '',
        addresscode: '',
        riverid: '',
        watergatename: '', //闸口名称
        address: '', //地址
        rivername: '', //所属河流
        watergatetype: '', //闸口类型
        watertype: '', //水体类型
        maxflow: '', //最大流量
        intercepttype: '', //闸坝类型
        longitude: '', //经度
        latitude: '', //纬度
        stream: '', //所属支流、干流
        regulationmode: '', //调度方式
        regulationunit: '', //调度单位
        openclose: true, //开启状态
        remark: '' // 备注
      };
    },
    async handleUpdate(data) {
      let id = data?.id || '';

      if (!id) {
        this.$message.error('请选择一条数据')
        return
      }
      let res = await getwatergateinfo(id);
      if (res.code == 200) {
        this.gateData = res.data
        this.gateData.openclose = res.data.openclose == 'true'
        this.dialogFormVisible = true;
      } else {
        this.$message.error(res.message)
      }

    },
    handleDelete(data) {
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deletewatergate(data?.id)
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    async deletewatergate(id) {
      try {
        // 如果没有传入id，则从选中列表中获取
        if (!id) {
          if (this.choseList.length === 0) {
            this.$message.error('请选择要删除的数据');
            return;
          }
          // 支持单个或批量删除
          id = this.choseList.map(item => item.id).join(',');
        }

        // 确认有要删除的ID
        if (!id) {
          this.$message.error('请选择要删除的数据');
          return;
        }

        // 执行删除操作
        const res = await removewatergate(id);
        if (res.code === 200) {
          this.$message.success('删除成功');
          this.query(); // 刷新列表
        } else {
          this.$message.error(res.message || '删除失败');
        }
      } catch (error) {
        this.$message.error('删除失败，请稍后重试');
        console.error(error);
      }
    },
    query() {

      this.getwatergateList()
    },
    async getwatergateList() {
      this.loading = true
      let { code, rows } = await getwatergateList({ address: this.address, watergatename: this.watergatename, riverid: this.riverid })
      if (code == 200) {
        this.tableData = rows
        this.tableData.forEach(item => {
          const watertype = this.dict.type.zk_water_type.find(typeItem => typeItem.value == item.watertype) || {}
          item.watertypename = watertype.label || ''
        })
      }
      this.loading = false
    },
    handleQuery() {
      this.query()
    },
    resetQuery() {
      this.address = ''
      this.watergatename = ''
      this.riverid = ''
    },

    addForm() {
      this.initFormData();
      this.dialogFormVisible = true;
    },
    async addSlice() {
      // 表单验证
      this.$refs.form.validate(async (valid) => {
        if (!valid) return;

        // 设置loading状态，防止重复提交
        this.submitLoading = true;

        try {
          let res;
          let params = { ...this.gateData };
          const region = this.regionList.find(regionItem => regionItem.code == params.addresscode);
          const watergatetype = this.dict.type.zk_water_gate_type.find(typeItem => typeItem.value == params.watergatetypecode)
          const river = this.riverList.find(riverItem => riverItem.value == params.riverid);
          // const watertype = this.dict.type.zk_water_type.find(typeItem => typeItem.value == params.watertype)
          params.address = region ? region.name : ''
          params.watergatetype = watergatetype ? watergatetype.label : ''
          // params.watertype = watertype ? watertype.label : ''
          params.rivername = river ? river.label : ''
          
          if (this.gateData.id) {
            // 编辑操作
            res = await editwatergate(params);
          } else {
            // 新增操作
            res = await addwatergate(params);
          }

          if (res.code === 200) {
            this.$message.success(`${this.gateData.id ? '编辑' : '新增'}成功`);
            this.dialogFormVisible = false;
            this.query(); // 刷新列表
          } else {
            this.$message.error(res.message || `${this.gateData.id ? '编辑' : '新增'}失败`);
          }
        } catch (error) {
          this.$message.error('操作失败，请稍后重试');
          console.error(error);
        } finally {
          this.submitLoading = false;
        }
      });
    },
    handleSelectionChange(val) {
      this.choseList = val;
    },
  }


};
</script>

<style lang="scss" scoped>
.sluice-header {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-bottom: 15px;
}

.zb-name {
  width: 300px;
}

.sluice-header-span {
  margin-left: 15px;
}

.query-btn {
  margin-left: 15px;
}

.sluice-sub-header {
  margin-bottom: 15px;
}

.select-width {
  // width: 307px;
  width: 100%;
}
</style>
